package com.lin.missyou.api.v1;

import com.lin.missyou.dto.TokenGetDTO;
import com.lin.missyou.dto.validators.TokenDTO;
import com.lin.missyou.exception.http.NotFoundException;
import com.lin.missyou.exception.http.ParameterException;
import com.lin.missyou.service.WxAuthenticationService;
import com.lin.missyou.util.JwtToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RequestMapping("token")
@RestController
public class TokenController {

    @Autowired
    private WxAuthenticationService wxAuthenticationService;

    /**
     * 对于微信小程序不需要password，只需要code码存放到account字段中
     *
     * @return Map<String, String>
     * 包装为map结构，返回到前端就是Object对象
     */
    @PostMapping("")
    public Map<String, String> getToken(@RequestBody @Validated TokenGetDTO userData) {
        Map<String, String> map = new HashMap<>();
        String token = null;
        switch (userData.getLoginType()) {
            case USER_WX:
                token = wxAuthenticationService.code2Session(userData.getAccount());
                break;
            case USER_Email:
                break;
            default:
                throw new NotFoundException(10003);
        }
        map.put("token", token);
        return map;
    }

    /**
     * 轻量接口，校验令牌
     * 不需要再申请token(重量级接口，请求微信服务器)
     * 令牌不是一次性的
     * @param tokenDTO
     * @return
     */
    @PostMapping("verify")
    public Map<String,Boolean> verify(@RequestBody  TokenDTO tokenDTO){
        Map<String,Boolean> map = new HashMap<>();
        String token = tokenDTO.getToken();
        Boolean valid = JwtToken.verify(token);
        map.put("is_valid",valid);
        return map;
    }
}
